package com.zy.web.controller;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.secure.BCrypt;
import com.zy.common.annotation.Log;
import com.zy.common.annotation.RepeatSubmit;
import com.zy.common.constant.Constants;
import com.zy.common.constant.UserConstants;
import com.zy.common.core.controller.BaseController;
import com.zy.common.core.domain.R;
import com.zy.common.core.domain.entity.SysUser;
import com.zy.common.core.domain.model.LoginBody;
import com.zy.common.core.domain.model.LoginUser;
import com.zy.common.enums.BusinessType;
import com.zy.common.helper.LoginHelper;
import com.zy.web.domain.ZyUser;
import com.zy.web.domain.vo.ZyUserVo;
import com.zy.web.service.IZySystemService;
import com.zy.web.service.IZyUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

/**
 * 系统接口
 *
 * @author zy
 * @date 2024-02-25
 */
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/web/system")
public class ZySystemController extends BaseController {

    private final IZySystemService loginService;
    private final IZyUserService userService;

    /**
     * 用户登录
     *
     * @param loginBody 主键
     */
    @PostMapping("/login")
    public R<Map<String, Object>> login(@RequestBody LoginBody loginBody) {
        Map<String, Object> ajax = new HashMap<>();
        // 生成令牌
        String token = loginService.login(loginBody.getUsername(), loginBody.getPassword(), loginBody.getCode(),
                loginBody.getUuid());
        ajax.put(Constants.TOKEN, token);
        ajax.put("id", LoginHelper.getLoginUser().getId());
//        ajax.put("id", token);
        /*Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")*/
        return R.ok(ajax);
    }

    /**
     * 用户注册
     */
    @SaCheckPermission("web:user:add")
    @Log(title = "用户", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/register")
    public R<Void> add(@RequestBody ZyUser bo) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(bo))) {
            return R.fail("新增用户'" + bo.getUsername() + "'失败，登录账号已存在");
        }
        bo.setPassword(BCrypt.hashpw(bo.getPassword()));
        return toAjax(userService.insertUser(bo));
    }
//

    /**
     * 获取用户信息
     *
     * @return 用户信息
     */
    @GetMapping("/getInfo")
    public R<Map<String, Object>> getInfo() {
        LoginUser loginUser = LoginHelper.getLoginUser();
        ZyUserVo userVo = userService.queryById(loginUser.getId());
        Map<String, Object> ajax = new HashMap<>();
        ajax.put("user", userVo);
        ajax.put("roles", loginUser.getRolePermission());
        ajax.put("permissions", loginUser.getMenuPermission());
        return R.ok(ajax);
    }

}
